﻿using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Web.Common;
using Web.Filters;

namespace Web.Controllers.API
{
    public class EmployeeController : ApiController
    {
        /// <summary>
        /// 添加职员
        /// </summary>
        /// <param name="Parid">父级ID</param>
        /// <param name="FullName">用户名</param>
        /// <param name="UserCode">用户编号</param>
        /// <param name="Tel">手机号</param>
        /// <param name="DtypeID">部门ID</param>
        /// <param name="Department">部门名</param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult InsertEmployee([FromBody]Models.API.Param.Employee entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.UserCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.FullName))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "FullName不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            try
            {
                string strSQL = "select typeid,fullname from Department where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.DtypeID);
                string dypeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();
                string dypename = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["fullname"].ToString();

                SqlParameter[] parameters = {
                    new SqlParameter("@Parid","00001"),//父节点ID
                    new SqlParameter("@DbName","employee"),
                    new SqlParameter("@UserCode",entity.UserCode),//编号
                    new SqlParameter("@FullName",entity.FullName),//名称*
                    new SqlParameter("@Department",string.IsNullOrWhiteSpace(entity.Department) ? dypename : entity.Department),//部门名称
                    new SqlParameter("@Tel",string.IsNullOrWhiteSpace(entity.Tel) ? "" : entity.Tel),//电话
                    new SqlParameter("@Address",null),
                    new SqlParameter("@Comment",null),
                    new SqlParameter("@BtypeID","00000"),
                    new SqlParameter("@Sex",null),
                    new SqlParameter("@Nation",null),
                    new SqlParameter("@Knowledge",null),
                    new SqlParameter("@Blood",null),
                    new SqlParameter("@Health",null),
                    new SqlParameter("@IDCard",null),
                    new SqlParameter("@BirthDay",null),
                    new SqlParameter("@Marriage",null),
                    new SqlParameter("@Job",null),
                    new SqlParameter("@Job2",null),
                    new SqlParameter("@Jobtime",null),
                    new SqlParameter("@Mob",null),
                    new SqlParameter("@Mail",null),
                    new SqlParameter("@Political",null),
                    new SqlParameter("@Nat_place",null),
                    new SqlParameter("@Tel2",null),
                    new SqlParameter("@College",null),
                    new SqlParameter("@For_language",null),
                    new SqlParameter("@Reg_place",null),
                    new SqlParameter("@Com_level",null),
                    new SqlParameter("@Weight",null),
                    new SqlParameter("@Stature",null),
                    new SqlParameter("@Fam_status",null),
                    new SqlParameter("@Informer",null),
                    new SqlParameter("@Speciality",null),
                    new SqlParameter("@For_lan_level",null),
                    new SqlParameter("@PostCode",null),
                    new SqlParameter("@DtypeID",dypeid),
                    new SqlParameter("@PyCode",""),
                    new SqlParameter("@MaxPre",999999999918.9900000000),
                    new SqlParameter("@tichengRate",null),
                    new SqlParameter("@STypeID","00001"),
                    new SqlParameter("@QQ",null),
                    new SqlParameter("@MSN",null),
                    new SqlParameter("@Blog",null),
                    new SqlParameter("@mBlog",null),
                    new SqlParameter("@Team",null),
                    new SqlParameter("@Buyerminvalue",0.0000000000),
                    new SqlParameter("@Saleminvalue",0.0000000000),
                    new SqlParameter("@ktypeid","")
                };
                
                parameters[46].Value = 0;
                parameters[47].Value = 0;

                //添加新用户
                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertE", parameters, out resultCount);

                ////添加操作员
                //string strSQL = "select typeid from employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.UserCode);
                //string etypeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();

                //SqlParameter[] param1 = {
                //    new SqlParameter("@szETypeID",etypeid),
                //    new SqlParameter("@operatorId","00001"),
                //    new SqlParameter("@isPos",0)
                //};
                //resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_AddNewLogin", param1, out resultCount);

                //if (resultCount == 0)
                //{
                //    //新增用户添加默认权限
                //    strSQL = "exec GP_UserRange_DefaultSetting";
                //    resultCount = FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, strSQL);

                //    //新增用户默认pos权限
                //    SqlParameter[] param2 = {
                //        new SqlParameter("@Operator",etypeid),
                //        new SqlParameter("@limits","2614,2616,2617,2618,2620,2621,2624,2628,2629,2630,2631,2935,5315"),
                //        new SqlParameter("@flag",1)
                //    };
                //    resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "GP_SetDefaulHaveLimit", param2, out resultCount);
                //}

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 修改职员
        /// </summary>
        /// <param name="Parid">父级ID</param>
        /// <param name="FullName">用户名</param>
        /// <param name="UserCode">用户编号</param>
        /// <param name="Tel">手机号</param>
        /// <param name="DtypeID">部门ID</param>
        /// <param name="Department">部门名</param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdateEmployee([FromBody]Models.API.Param.Employee entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            
            if (string.IsNullOrWhiteSpace(entity.UserCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.FullName))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "FullName不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            try
            {

                string strSQL = "select typeid from Employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.UserCode);
                string typeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();

                strSQL = "select typeid,fullname from Department where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.DtypeID);
                string dypeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();
                string dypename = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["fullname"].ToString();

                SqlParameter[] parameters = {
                    new SqlParameter("@Typeid",typeid),//职员ID
                    new SqlParameter("@UserCode",entity.UserCode),//编号
                    new SqlParameter("@FullName",entity.FullName),//名称*
                    new SqlParameter("@Department",string.IsNullOrWhiteSpace(entity.Department) ? dypename : entity.Department),//部门名称
                    new SqlParameter("@Tel",string.IsNullOrWhiteSpace(entity.Tel) ? "" : entity.Tel),//电话
                    new SqlParameter("@Address",null),
                    new SqlParameter("@Comment",null),
                    new SqlParameter("@BtypeID","00000"),
                    new SqlParameter("@Sex",null),
                    new SqlParameter("@Nation",null),
                    new SqlParameter("@Knowledge",null),
                    new SqlParameter("@Blood",null),
                    new SqlParameter("@Health",null),
                    new SqlParameter("@IDCard",null),
                    new SqlParameter("@BirthDay",null),
                    new SqlParameter("@Marriage",null),
                    new SqlParameter("@Job",null),
                    new SqlParameter("@Job2",null),
                    new SqlParameter("@Jobtime",null),
                    new SqlParameter("@Mob",null),
                    new SqlParameter("@Mail",null),
                    new SqlParameter("@Political",null),
                    new SqlParameter("@Nat_place",null),
                    new SqlParameter("@Tel2",null),
                    new SqlParameter("@College",null),
                    new SqlParameter("@For_language",null),
                    new SqlParameter("@Reg_place",null),
                    new SqlParameter("@Com_level",null),
                    new SqlParameter("@Weight",null),
                    new SqlParameter("@Stature",null),
                    new SqlParameter("@Fam_status",null),
                    new SqlParameter("@Informer",null),
                    new SqlParameter("@Speciality",null),
                    new SqlParameter("@For_lan_level",null),
                    new SqlParameter("@PostCode",null),
                    new SqlParameter("@DtypeID",dypeid),
                    new SqlParameter("@PyCode",""),
                    new SqlParameter("@MaxPre",999999999918.9900000000),
                    new SqlParameter("@tichengRate",null),
                    new SqlParameter("@STypeID","00001"),
                    new SqlParameter("@QQ",null),
                    new SqlParameter("@MSN",null),
                    new SqlParameter("@Blog",null),
                    new SqlParameter("@mBlog",null),
                    new SqlParameter("@Team",null),
                    new SqlParameter("@Buyerminvalue",0.0000000000),
                    new SqlParameter("@Saleminvalue",0.0000000000),
                    new SqlParameter("@ktypeid","")
                };

                parameters[45].Value = 0;
                parameters[46].Value = 0;

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString,"Gp_UpdateE", parameters, out resultCount);

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 删除职员
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteEmployee([FromBody]Models.API.Param.Employee entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            
            //if (string.IsNullOrWhiteSpace(entity.TypeId))
            //{
            //    result.Type = AjaxResultType.Warning;
            //    result.Content = "TypeId不可为空";
            //    return Json(result);
            //}

            try
            {
                SqlParameter[] parameters = {
                    new SqlParameter("@typeid",SqlDbType.VarChar,100),
                    new SqlParameter("@dbname",SqlDbType.VarChar,100),
                    new SqlParameter("@deltype",SqlDbType.Int)
                };

                string strSQL = "select typeid from Employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.UserCode);
                string typeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();
                
                parameters[0].Value = typeid;
                parameters[1].Value = "Employee";
                parameters[2].Value = 0;

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString,"Gp_StopBaseInfo", parameters, out resultCount);

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.TotalRows = 0;
                result.Data = "Error";
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 查询职员
        /// </summary>
        /// <param name="TypeId">职员ID</param>
        /// <param name="UserCode">编号</param>
        /// <param name="FullName">名称</param>
        /// <param name="Department">部门</param>
        /// <param name="Delfg">删除标识</param>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">每页大小</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SelectEmployee(dynamic dyobj)
        {
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }

            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            string strSQL;
            
            try
            {
                strSQL = "";
                strSQL += "select ";
                //strSQL += " typeId ";
                strSQL += "  employee.UserCode ";
                strSQL += " ,employee.FullName ";
                strSQL += " ,employee.DtypeID ";
                strSQL += " ,d.usercode DepartCode";
                strSQL += " ,employee.Department ";
                strSQL += " ,isnull(employee.Tel,'') as Tel ";
                strSQL += " ,employee.deleted ";
                strSQL += " from employee ";
                strSQL += " inner join Department as d on d.typeid = employee.DtypeID ";
                strSQL += " where 1=1 ";


                string sqlstrcount = "";

                sqlstrcount += "select count(*) from employee ";
                sqlstrcount += " where 1=1 ";

                //if (null != mydyobj.TypeId && !string.IsNullOrWhiteSpace(mydyobj.TypeId.ToString()))
                //    strSQL += " and typeId = N'" + mydyobj.TypeId.ToString().Replace("'", "''") + "'";

                if (null != mydyobj.UserCode && !string.IsNullOrWhiteSpace(mydyobj.UserCode.ToString())) { 
                    strSQL += " and employee.UserCode = N'" + mydyobj.UserCode.ToString().Replace("'", "''") + "'";
                sqlstrcount += " and UserCode = N'" + mydyobj.UserCode.ToString().Replace("'", "''") + "'";
                }
                if (null != mydyobj.FullName && !string.IsNullOrWhiteSpace(mydyobj.FullName.ToString())) { 
                    strSQL += " and employee.FullName like '%" + mydyobj.FullName.ToString() + "%'";
                sqlstrcount += " and FullName like '%" + mydyobj.FullName.ToString() + "%'";
                }
                if (null != mydyobj.Department && !string.IsNullOrWhiteSpace(mydyobj.Department.ToString())) {
                    strSQL += " and employee.Department like '%" + mydyobj.Department.ToString() + "%'";
                sqlstrcount += " and Department like '%" + mydyobj.Department.ToString() + "%'";
                }
                if (null != mydyobj.Delfg && "0".Equals(mydyobj.Delfg.ToString())) { 
                    strSQL += " and employee.deleted = '0'";
                sqlstrcount += " and deleted = '0'";
                }

                strSQL += " order by employee.typeid asc ";

                if (!"0".Equals(mydyobj.PageIndex.ToString()) && !"0".Equals(mydyobj.PageSize.ToString()))
                {
                    strSQL += " offset " + (Convert.ToInt32(mydyobj.PageIndex.ToString()) - 1) * Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows fetch next " + Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows only";
                }




                result.TotalRows = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(sqlstrcount));

                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;
             //   result.TotalRows = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }
        


    }
}